from django.http import HttpResponse
from captcha.models import CaptchaStore

import json

from aiapi.models.users import Users


def captcha_check(request):
    '''
    验证
    POST
    re = {
        "key": "874ffa339858419be50475077b49638403392d15",
        "text": "1234"
    }
    '''
    # 验证验证码
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        re_key = json_obj['key']
        re_text = str(json_obj['text']).lower()

        try:
            captcha = CaptchaStore.objects.get(hashkey=re_key)
        except:
            res_mes = {
                "code": 1,
                "data": "验证码错误"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        captcha_response = captcha.response
        if re_text == captcha_response:
            res_mes = {
                "code": 0
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        else:
            res_mes = {
                "code": 1,
                "data": "验证码错误"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)


def captcha_checkuser(request):
    '''
    检测用户是否存在
    咱们没写完
    re = {
        "receiver": "18201419965"
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        re_user_obj = Users.objects.filter(username=json_obj['receiver'])
        if re_user_obj:
            res_mes = {
                "code": 1,
                "message": "该用户名已经被注册"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json) 

        res_mes = {
            "code": 0,
            "message": None
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json) 

